<template>
  <el-dialog v-model="dialogVisible" :title="parameter.title" width="680px" lock-scroll destroy-on-close draggable>
    <el-form ref="formRef" :model="parameter.org" :rules="rules" label-width="100px" label-suffix=" :">
      <el-form-item label="上级目录" prop="pid">
        <el-cascader
          v-model="parameter.org.pid"
          :options="formInline.higherOrgOptions"
          :props="{ checkStrictly: true, emitPath: false }"
          style="width: 100%"
          clearable
          filterable
          placeholder="请选择上级目录"
        >
          <template #default="{ node, data }">
            <span>{{ data.label }}</span>
            <span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
          </template>
        </el-cascader>
      </el-form-item>
      <el-form-item label="机构名称" prop="name">
        <el-input v-model="parameter.org.name" placeholder="请填写机构名称" clearable />
      </el-form-item>
      <el-form-item label="机构编号" prop="number">
        <el-input v-model="parameter.org.number" placeholder="请填写机构编号" clearable />
      </el-form-item>
      <el-form-item label="备注说明" prop="remarks">
        <el-input v-model="parameter.org.remarks" type="textarea" placeholder="请填写备注说明" clearable />
      </el-form-item>
      <el-form-item label="权重(排序)" prop="sort">
        <el-input-number v-model="parameter.org.sort" :precision="0" :value-on-clear="0" :min="0" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="handleSubmit">提交</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts" name="orgEdit">
import type { ResultData, Option, SysOrg } from "@/api/interface";
import type { FormInstance, FormRules } from "element-plus";
import { ref, reactive, watch } from "vue";
import { FormEnum } from "@/enums/formEnum";
import { getOrgCascaderOptionApi } from "@/api/modules/system/org";
import { ElMessage } from "element-plus";

/** 系统机构 */
interface EditProps {
  /** 标题 */
  title: string;
  /** 待编辑的机构 */
  org: Partial<SysOrg.Form>;
  /** 获取表格数据的Api */
  getTableList?: () => void;
  /** 提交表单的Api */
  submitApi?: (params: any) => Promise<ResultData<boolean>>;
}

/** 表单内联数据 */
interface FormInline {
  /** 上级机构选项 */
  higherOrgOptions: Option.CascadeOption[];
}

/** 表单实例 */
const formRef = ref<FormInstance>();
/** dialog 状态 */
const dialogVisible = ref(false);
/** 表单校验规则 */
const rules = reactive<FormRules>({
  name: [{ required: true, message: "请输入机构名称", trigger: "blur" }],
  number: [{ required: true, message: "请输入机构编号", trigger: "blur" }]
});
/** 父组件传过来的参数 */
const parameter = ref<EditProps>({
  title: "",
  org: {
    sort: 0
  }
});
/** 表单在线数据 */
const formInline = reactive<FormInline>({
  higherOrgOptions: []
});

/**
 * 接收父组件参数
 *
 * @param params 父组件传过来的参数
 * @returns void
 */
const acceptParams = (params: EditProps) => {
  parameter.value = params;
  dialogVisible.value = true;
};

/**
 * 初始化表单数据
 *
 * 1. 重置表单
 * 2. 获取上级机构选项
 * 3. 加载表单数据
 *
 * @returns void
 */
const initFormInline = () => {
  formRef.value?.resetFields();
  formInline.higherOrgOptions = [];

  getOrgCascaderOptionApi().then(({ data }) => {
    formInline.higherOrgOptions = data;
  });
};

/**
 * 提交页面上的数据
 *
 * 1. 校验表单
 * 2. 表单数据处理
 * 3. 提交表单
 * 4. 提交结果处理
 * 5. 异常处理
 *
 * @returns void
 */
const handleSubmit = () => {
  formRef.value
    // 1. 校验表单
    ?.validate()
    // 2. 表单数据处理
    .then(() => {
      parameter.value.org = {
        id: parameter.value.org.id || FormEnum.EmptyId,
        pid: parameter.value.org.pid || FormEnum.EmptyId,
        name: parameter.value.org.name,
        number: parameter.value.org.number || "",
        remarks: parameter.value.org.remarks || "",
        sort: parameter.value.org.sort || 0
      };

      return parameter.value.org;
    })
    // 3. 提交表单
    .then(org => {
      return parameter.value.submitApi!(org);
    })
    // 4. 提交结果处理
    .then(({ data }) => {
      if (data) {
        ElMessage.success({ message: `${parameter.value.title}成功！` });
        parameter.value.getTableList!();
        dialogVisible.value = false;
      } else {
        ElMessage.error({ message: `${parameter.value.title}失败！` });
      }
    })
    // 5. 异常处理
    .catch((error: Error) => {
      if (error.message) ElMessage.error({ message: `${parameter.value.title}异常：${error.message}` });
      else ElMessage.error({ message: "请检查表单数据是否填写完整！" });
    });
};

// 监听 dialogVisible 的变化
watch(dialogVisible, val => {
  if (val) {
    initFormInline();
  }
});

// 暴露给父组件的属性和方法
defineExpose({
  acceptParams
});
</script>
